package com.ruoyi.storage.service.impl;

import java.util.List;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.order.domain.SalesDetail;
import com.ruoyi.order.domain.SalesOrder;
import com.ruoyi.order.service.impl.SalesDetailServiceImpl;
import com.ruoyi.order.service.impl.SalesOrderServiceImpl;
import com.ruoyi.storage.domain.*;
import com.ruoyi.storage.mapper.ItemDetailMapper;
import com.ruoyi.storage.mapper.WarehouseInfoMapper;
import com.ruoyi.storage.mapper.WarehouseInventoryMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.storage.mapper.ExitRecordMapper;
import com.ruoyi.storage.service.IExitRecordService;

/**
 * 出库Service业务层处理
 * 
 * @author 庞一恺
 * @date 2025-01-23
 */
@Service
public class ExitRecordServiceImpl implements IExitRecordService 
{
    @Autowired
    private ExitRecordMapper exitRecordMapper;
    @Autowired
    private WarehouseInfoServiceImpl warehouseInfoServiceImpl;
    @Autowired
    private WarehouseInfoMapper warehouseInfoMapper;
    @Autowired
    private ItemDetailMapper itemDetailMapper;
    @Autowired
    private WarehouseInventoryMapper warehouseInventoryMapper;
    @Autowired
    private SalesOrderServiceImpl salesOrderServiceImpl;
    @Autowired
    private SalesDetailServiceImpl salesDetailServiceImpl;
    @Autowired
    private StoSalesDetailServiceImpl stoSalesDetailServiceImpl;

    /**
     * 查询出库
     * 
     * @param outId 出库主键
     * @return 出库
     */
    @Override
    public ExitRecord selectExitRecordByOutId(Integer outId)
    {
        return exitRecordMapper.selectExitRecordByOutId(outId);
    }

    /**
     * 查询出库列表
     * 
     * @param exitRecord 出库
     * @return 出库
     */
    @Override
    public List<ExitRecord> selectExitRecordList(ExitRecord exitRecord)
    {
        return exitRecordMapper.selectExitRecordList(exitRecord);
    }

    /**
     * 新增出库
     * 
     * @param exitRecord 出库
     * @return 结果
     */
    @Transactional
    @Override
    public int insertExitRecord(ExitRecord exitRecord)
    {
        int rows = exitRecordMapper.insertExitRecord(exitRecord);
        insertExitDetail(exitRecord);
        return rows;
    }

    /**
     * 修改出库
     * 
     * @param exitRecord 出库
     * @return 结果
     */
    @Transactional
    @Override
    public int updateExitRecord(ExitRecord exitRecord)
    {
        exitRecordMapper.deleteExitDetailByExitRecordId(exitRecord.getOutId());
        insertExitDetail(exitRecord);
        return exitRecordMapper.updateExitRecord(exitRecord);
    }

    /**
     * 批量删除出库
     * 
     * @param outIds 需要删除的出库主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteExitRecordByOutIds(Integer[] outIds)
    {
        exitRecordMapper.deleteExitDetailByExitRecordIds(outIds);
        return exitRecordMapper.deleteExitRecordByOutIds(outIds);
    }

    /**
     * 删除出库信息
     * 
     * @param outId 出库主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteExitRecordByOutId(Integer outId)
    {
        exitRecordMapper.deleteExitDetailByExitRecordId(outId);
        return exitRecordMapper.deleteExitRecordByOutId(outId);
    }

    /**
     * 订单出库
     *
     * @param productList，orderId
     * @return 结果
     */
    @Override
    public int salesExit(List<String> productList, String orderId) {

        WarehouseInfo warehouseInfo = warehouseInfoServiceImpl.selectWarehouseInfoByWarehouseId(warehouseInfoMapper.getWarehouseIdByPrincipal(Math.toIntExact(SecurityUtils.getUserId())));

        ExitRecord exitRecord = new ExitRecord();
        exitRecord.setOutcomeType("订单出库");
        exitRecord.setOutcomeState("待取件");
        exitRecord.setEvidenceRecordId(orderId);
        exitRecord.setWarehouseId(warehouseInfo.getWarehouseId());
        exitRecord.setGeneratedBy(String.valueOf(SecurityUtils.getUsername()));
        exitRecord.setOutcomeDate(DateUtils.getNowDate());
        exitRecord.setOrigin(warehouseInfo.getWarehouseName());






        //TODO 出库单详情


        Long totalWeight = 0L;

        List<String> batchList = new ArrayList<>();
        List<ExitDetail> exitDetailList = new ArrayList<>();

        for (String product : productList){

            ItemDetail itemDetail = itemDetailMapper.selectItemDetailByItemId(product);
            if (itemDetail == null) return 0;
            WarehouseInventory warehouseInventory = warehouseInventoryMapper.selectWarehouseInventoryByBatchId(itemDetail.getBatchId());

            if (!batchList.contains(itemDetail.getBatchId())){
                batchList.add(itemDetail.getBatchId());

                ExitDetail exitDetail = new ExitDetail();

                exitDetail.setBatchId(itemDetail.getBatchId());
                exitDetail.setOrderNo(orderId);
                exitDetail.setRawProductName(warehouseInventory.getInventoryName());
                exitDetail.setWeight(itemDetail.getWeight());
                exitDetail.setWeightUnit("克");
                exitDetail.setTransportQuantity(1L);
                exitDetail.setStatus("未送达");
                exitDetail.setExitType("订单出库");
                exitDetail.setOrigin(warehouseInventory.getOrigin());
                exitDetail.setGoodSpecification(warehouseInventory.getGoodSpecification());
                exitDetail.setMerchandiseKind(warehouseInventory.getRawProductId());
                exitDetail.setManufactureDate(warehouseInventory.getCreateTime());
                exitDetail.setWarehouseId(itemDetail.getWarehouseId());
                exitDetail.setAreaId(itemDetail.getAreaId());

                exitDetailList.add(exitDetail);
            }else {
                exitDetailList.forEach(exitDetail -> {
                    if (exitDetail.getBatchId().equals(itemDetail.getBatchId())){
                        exitDetail.setWeight(exitDetail.getWeight() + itemDetail.getWeight());
                        exitDetail.setTransportQuantity(exitDetail.getTransportQuantity() + 1);
                    }
                });
            }



            totalWeight += itemDetail.getWeight();
        }
        exitRecord.setWeight(totalWeight/1000);
        exitRecord.setTransportQuantity(Long.valueOf(exitDetailList.size()));
        exitRecord.setWeightUnit("千克");
        exitRecord.setDestination(salesOrderServiceImpl.selectSalesOrderByOrderId(orderId).getAddressId());
        exitRecord.setState("送往配送");
        exitRecord.setCreatedTime(DateUtils.getNowDate());


        int i = exitRecordMapper.insertExitRecord(exitRecord);


        for (ExitDetail exitDetail : exitDetailList){
            exitDetail.setExitRecordId(exitRecord.getOutId());
            exitRecord.getExitDetailList().add(exitDetail);
        }


        exitRecordMapper.batchExitDetail(exitRecord.getExitDetailList());

        //TODO 修改订单详情状态
        //修改本次出库对应的订单详情（本仓库部分）改为已发货（4-5）
        salesDetailStateUpdateInExit(orderId, exitRecord.getWarehouseId());




        return i;
    }

    /**
     * 修改订单详情状态
     *
     * @param orderId 订单详情编号
     * @param warehouseId 仓库编号
     */

    // TODO salesDetailServiceImpl里面调用的salesDetailMapper里面的SQL语句没有加上对新增字段status的修改。
    private void salesDetailStateUpdateInExit(String orderId, Integer warehouseId) {
        List<SalesDetail> salesDetailList = exitRecordMapper.getSalesDetailListInExit(orderId, warehouseId);
        for (SalesDetail salesDetail : salesDetailList){
            salesDetail.setStatus("5");
            salesDetailServiceImpl.updateSalesDetail(salesDetail);
        }
        salesDetailList = exitRecordMapper.selectSalesDetailListByOrderId(orderId);
        //如果订单详情状态全部改为已发货，则修改salesOrder状态为已发货
        if (salesDetailList.stream().allMatch(salesDetail -> salesDetail.getStatus().equals("5"))){
            SalesOrder salesOrder = salesOrderServiceImpl.selectSalesOrderByOrderId(orderId);
            salesOrder.setOrderStatus("5");
            salesOrderServiceImpl.updateSalesOrder(salesOrder);
        }
    }


    /**
     * 新增出库详情信息
     * 
     * @param exitRecord 出库对象
     */
    public void insertExitDetail(ExitRecord exitRecord)
    {
        List<ExitDetail> exitDetailList = exitRecord.getExitDetailList();
        Integer outId = exitRecord.getOutId();
        if (StringUtils.isNotNull(exitDetailList))
        {
            List<ExitDetail> list = new ArrayList<ExitDetail>();
            for (ExitDetail exitDetail : exitDetailList)
            {
                exitDetail.setExitRecordId(outId);
                list.add(exitDetail);
            }
            if (list.size() > 0)
            {
                exitRecordMapper.batchExitDetail(list);
            }
        }
    }
}
